<script setup lang="tsx">
import { ref } from 'vue';
import type { Ref } from 'vue';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { fetchBatchDeleteDepartment, fetchGetDepartmentList } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { useAuth } from '@/hooks/business/auth';
import { enableStatusRecord } from '@/constants/business';
import DeptOperateDrawer, { type OperateType } from './modules/dept-operate-drawer.vue';
const { hasAuth } = useAuth();
const appStore = useAppStore();
const { bool: visible, setTrue: openModal } = useBoolean();

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetDepartmentList,
  apiParams: {
    current: 1,
    size: 10
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'id',
      title: $t('common.index'),
      width: 64,
      align: 'center'
    },
    {
      key: 'deptName',
      title: '部门名称',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'phone',
      title: '电话',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'leader',
      title: '负责人',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'orderNum',
      title: '部门顺序',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'remark',
      title: '描述',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      minWidth: 120,
      render(row) {
        if (row.status === null) {
          return null;
        }

        const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
          1: 'success',
          2: 'warning'
        };

        const label = $t(enableStatusRecord[row.status]);

        return <NTag type={tagMap[row.status]}>{label}</NTag>;
      }
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      minWidth: 50,
      render(row) {
        return (
          <div class="flex-center gap-8px">
            <NButton
              v-if={() => hasAuth('system:user:add')}
              type="info"
              ghost
              size="small"
              onClick={() => handleAddChild(row)}
            >
              新增子部门
            </NButton>
            <NButton
              v-if={() => hasAuth('system:user:update')}
              type="primary"
              ghost
              size="small"
              onClick={() => handleEdit(row)}
            >
              {$t('common.edit')}
            </NButton>
          </div>
        );
      }
    }
  ]
});

const { checkedRowKeys, onBatchDeleted, onDeleted } = useTableOperate(data, getData);

const operateType = ref<OperateType>('add');

async function handleBatchDelete() {
  // request
  console.log(checkedRowKeys.value);
  const { error } = await fetchBatchDeleteDepartment(checkedRowKeys.value);
  if (error) return;
  onBatchDeleted();
}

function handleDelete(id: number) {
  // request
  console.log(id);

  onDeleted();
}
const editingData: Ref<Api.SystemManage.Dept | null> = ref(null);
function handleEdit(item: Api.SystemManage.Dept) {
  operateType.value = 'edit';
  editingData.value = { ...item };

  openModal();
}
function handleAdd() {
  operateType.value = 'add';
  editingData.value = null;

  openModal();
}

// 新增子部门
function handleAddChild(item: Api.SystemManage.Dept) {
  operateType.value = 'addChild';
  editingData.value = { ...item };

  openModal();
}

// function edit(id: number) {
//   handleEdit(id);
// }
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="部门列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation v-model:columns="columnChecks" :loading="loading" @refresh="getData">
          <template #prefix>
            <NButton v-if="hasAuth('system:dept:add')" size="small" ghost type="primary" @click="handleAdd">
              <template #icon>
                <icon-ic-round-plus class="text-icon" />
              </template>
              {{ $t('common.add') }}
            </NButton>
            <NPopconfirm v-if="hasAuth('system:user:delete')" @positive-click="handleBatchDelete">
              <template #trigger>
                <NButton size="small" ghost type="error" :disabled="checkedRowKeys.length === 0">
                  <template #icon>
                    <icon-ic-round-delete class="text-icon" />
                  </template>
                  {{ $t('common.batchDelete') }}
                </NButton>
              </template>
              {{ $t('common.confirmDelete') }}
            </NPopconfirm>
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="702"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <DeptOperateDrawer
        v-model:visible="visible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
